package com.sanq.product.books.controller;

import com.sanq.product.books.config.Redis;
import com.sanq.product.books.entity.vo.CollectionVo;
import com.sanq.product.books.entity.vo.UsersVo;
import com.sanq.product.books.service.CollectionService;
import com.sanq.product.books.utils.WebUtil;
import com.sanq.product.config.utils.annotation.LogAnnotation;
import com.sanq.product.config.utils.entity.Pager;
import com.sanq.product.config.utils.entity.Pagination;
import com.sanq.product.config.utils.entity.Response;
import com.sanq.product.config.utils.web.JsonUtil;
import com.sanq.product.redis.service.JedisPoolService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/app/collection")
public class CollectionController {

	@Resource
	private CollectionService collectionService;
	@Resource
	private JedisPoolService jedisPoolService;


	@LogAnnotation(description = "删除数据")
	@DeleteMapping(value="/delete")
	public Response deleteById(HttpServletRequest request, @RequestBody CollectionVo collectionVo) {

		int result = collectionService.delete(collectionVo);
		return result == 1 ? new Response().success() : new Response().failure();
	}

	@LogAnnotation(description = "分页查询数据")
	@GetMapping(value="/list")
	public Response findListByPager(HttpServletRequest request, CollectionVo collectionVo, Pagination pagination) {

		UsersVo usersVo = JsonUtil.json2Obj(jedisPoolService.get(Redis.ReplaceKey.getTokenUser(WebUtil.getToken(request))), UsersVo.class);

		collectionVo.setUserId(usersVo.getId());
		Pager<CollectionVo> pager = collectionService.findListByPage(collectionVo, pagination);

		return pager != null ? new Response().success(pager) : new Response().failure();
	}

	@LogAnnotation(description = "添加数据")
	@PostMapping(value="/save")
	public Response add(HttpServletRequest request, @RequestBody CollectionVo collectionVo) {

		UsersVo usersVo = JsonUtil.json2Obj(jedisPoolService.get(Redis.ReplaceKey.getTokenUser(collectionVo.getToken())), UsersVo.class);

		int result = 0;
		if(collectionVo.isCollection()) {
			collectionVo.setUserId(usersVo.getId());
			result = collectionService.save(collectionVo);
		} else {
			CollectionVo params = new CollectionVo();
			params.setUserId(usersVo.getId());
			params.setBookId(collectionVo.getBookId());
			result = collectionService.delete(params);
		}

		return result == 1 ? new Response().success() : new Response().failure();
	}

	@LogAnnotation(description = "通过ID修改数据")
	@PutMapping(value="/update/{id}")
	public Response updateByKey(HttpServletRequest request,
        @RequestBody CollectionVo collectionVo,
        @PathVariable("id") Integer id) {

		int result = collectionService.update(collectionVo, id);

		return result == 1 ? new Response().success() : new Response().failure();
	}
}